package com.gc.business.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gc.business.domain.CommunityManage;
import com.gc.business.domain.ElevatorInfo;
import com.gc.business.mapper.ElevatorInfoMapper;
import com.gc.business.service.IElevatorInfoService;
import com.gc.common.config.Global;
import com.gc.common.utils.StringUtils;
import com.gc.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 电梯 服务层实现
 *
 * @author liujinteng
 * @date 2020-11-13
 */
@Slf4j
@Service
public class ElevatorInfoServiceImpl extends ServiceImpl<ElevatorInfoMapper, ElevatorInfo> implements IElevatorInfoService {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ElevatorInfoMapper elevatorInfoMapper;

    @Override
    public List<ElevatorInfo> list(ElevatorInfo elevatorInfo,List<Long> collect) {
        LambdaQueryWrapper<ElevatorInfo> wrapper = new LambdaQueryWrapper<>();
        if (elevatorInfo != null) {
            if (StringUtils.isNotEmpty(elevatorInfo.getElevatorId())) {
                wrapper.eq(ElevatorInfo::getElevatorId, elevatorInfo.getElevatorId());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getElevatorName())) {
                wrapper.like(ElevatorInfo::getElevatorName, elevatorInfo.getElevatorName());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getNumberCode())) {
                wrapper.eq(ElevatorInfo::getNumberCode, elevatorInfo.getNumberCode());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getRegisteredCode())) {
                wrapper.eq(ElevatorInfo::getRegisteredCode, elevatorInfo.getRegisteredCode());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getIdentifyCode())) {
                wrapper.eq(ElevatorInfo::getIdentifyCode, elevatorInfo.getIdentifyCode());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getElevatorBrand())) {
                wrapper.eq(ElevatorInfo::getElevatorBrand, elevatorInfo.getElevatorBrand());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getLayerNum())) {
                wrapper.eq(ElevatorInfo::getLayerNum, elevatorInfo.getLayerNum());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getStandingNum())) {
                wrapper.eq(ElevatorInfo::getStandingNum, elevatorInfo.getStandingNum());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getInstallationDate())) {
                wrapper.eq(ElevatorInfo::getInstallationDate, elevatorInfo.getInstallationDate());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getAnnualDate())) {
                wrapper.eq(ElevatorInfo::getAnnualDate, elevatorInfo.getAnnualDate());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getNextAnnualDate())) {
                wrapper.eq(ElevatorInfo::getNextAnnualDate, elevatorInfo.getNextAnnualDate());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getUseUnit())) {
                wrapper.like(ElevatorInfo::getUseUnit, elevatorInfo.getUseUnit());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getElevatorAdministrator())) {
                wrapper.like(ElevatorInfo::getElevatorAdministrator, elevatorInfo.getElevatorAdministrator());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getMaintenanceUnit())) {
                wrapper.like(ElevatorInfo::getMaintenanceUnit, elevatorInfo.getMaintenanceUnit());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getMaintenanceEngineer())) {
                wrapper.eq(ElevatorInfo::getMaintenanceEngineer, elevatorInfo.getMaintenanceEngineer());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getNetworkStatus())) {
                wrapper.eq(ElevatorInfo::getNetworkStatus, elevatorInfo.getNetworkStatus());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getNetworkDate())) {
                wrapper.eq(ElevatorInfo::getNetworkDate, elevatorInfo.getNetworkDate());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getElevatorStatus())) {
                wrapper.eq(ElevatorInfo::getElevatorStatus, elevatorInfo.getElevatorStatus());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getCheckFix())) {
                wrapper.eq(ElevatorInfo::getCheckFix, elevatorInfo.getCheckFix());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getBuildingUnit())) {
                wrapper.like(ElevatorInfo::getBuildingUnit, elevatorInfo.getBuildingUnit());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getLongitude())) {
                wrapper.eq(ElevatorInfo::getLongitude, elevatorInfo.getLongitude());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getLatitude())) {
                wrapper.eq(ElevatorInfo::getLatitude, elevatorInfo.getLatitude());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getUsePlace())) {
                wrapper.eq(ElevatorInfo::getUsePlace, elevatorInfo.getUsePlace());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getBuildType())) {
                wrapper.eq(ElevatorInfo::getBuildType, elevatorInfo.getBuildType());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getElevatorType())) {
                wrapper.eq(ElevatorInfo::getElevatorType, elevatorInfo.getElevatorType());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getVendor())) {
                wrapper.like(ElevatorInfo::getVendor, elevatorInfo.getVendor());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getProductionDate())) {
                wrapper.eq(ElevatorInfo::getProductionDate, elevatorInfo.getProductionDate());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getUseType())) {
                wrapper.eq(ElevatorInfo::getUseType, elevatorInfo.getUseType());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getRatedLoad())) {
                wrapper.eq(ElevatorInfo::getRatedLoad, elevatorInfo.getRatedLoad());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getBumperType())) {
                wrapper.eq(ElevatorInfo::getBumperType, elevatorInfo.getBumperType());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getModelNumber())) {
                wrapper.eq(ElevatorInfo::getModelNumber, elevatorInfo.getModelNumber());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getFactoryCode())) {
                wrapper.eq(ElevatorInfo::getFactoryCode, elevatorInfo.getFactoryCode());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getNominal())) {
                wrapper.eq(ElevatorInfo::getNominal, elevatorInfo.getNominal());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getInstallUnit())) {
                wrapper.like(ElevatorInfo::getInstallUnit, elevatorInfo.getInstallUnit());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getPromoteHeight())) {
                wrapper.eq(ElevatorInfo::getPromoteHeight, elevatorInfo.getPromoteHeight());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getTractorPower())) {
                wrapper.eq(ElevatorInfo::getTractorPower, elevatorInfo.getTractorPower());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getStandardFloorHeight())) {
                wrapper.eq(ElevatorInfo::getStandardFloorHeight, elevatorInfo.getStandardFloorHeight());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getSpeedGovernor())) {
                wrapper.eq(ElevatorInfo::getSpeedGovernor, elevatorInfo.getSpeedGovernor());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getSpecialEquipmentCode())) {
                wrapper.eq(ElevatorInfo::getSpecialEquipmentCode, elevatorInfo.getSpecialEquipmentCode());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getIssueDate())) {
                wrapper.eq(ElevatorInfo::getIssueDate, elevatorInfo.getIssueDate());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getSpecialEquipmentRegistration())) {
                wrapper.eq(ElevatorInfo::getSpecialEquipmentRegistration, elevatorInfo.getSpecialEquipmentRegistration());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getInspectionReportNum())) {
                wrapper.eq(ElevatorInfo::getInspectionReportNum, elevatorInfo.getInspectionReportNum());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getInspectionReport())) {
                wrapper.eq(ElevatorInfo::getInspectionReport, elevatorInfo.getInspectionReport());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getSpecialEquipmentUseFlag())) {
                wrapper.eq(ElevatorInfo::getSpecialEquipmentUseFlag, elevatorInfo.getSpecialEquipmentUseFlag());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getApprovalNumber())) {
                wrapper.eq(ElevatorInfo::getApprovalNumber, elevatorInfo.getApprovalNumber());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getApprovalName())) {
                wrapper.eq(ElevatorInfo::getApprovalName, elevatorInfo.getApprovalName());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getApprovalType())) {
                wrapper.like(ElevatorInfo::getApprovalType, elevatorInfo.getApprovalType());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getApprovalUnit())) {
                wrapper.like(ElevatorInfo::getApprovalUnit, elevatorInfo.getApprovalUnit());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getApprovalDate())) {
                wrapper.eq(ElevatorInfo::getApprovalDate, elevatorInfo.getApprovalDate());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getRemark())) {
                wrapper.like(ElevatorInfo::getRemark, elevatorInfo.getRemark());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getCreateBy())) {
                wrapper.eq(ElevatorInfo::getCreateBy, elevatorInfo.getCreateBy());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getCreateTime())) {
                wrapper.eq(ElevatorInfo::getCreateTime, elevatorInfo.getCreateTime());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getUpdateBy())) {
                wrapper.eq(ElevatorInfo::getUpdateBy, elevatorInfo.getUpdateBy());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getUpdateTime())) {
                wrapper.eq(ElevatorInfo::getUpdateTime, elevatorInfo.getUpdateTime());
            }
            if (StringUtils.isNotEmpty(elevatorInfo.getBelongCommunity())) {
                wrapper.eq(ElevatorInfo::getBelongCommunity, elevatorInfo.getBelongCommunity());
            }
            //社区挂钩
            if (CollUtil.isNotEmpty(collect)){
                wrapper.in(ElevatorInfo::getBelongCommunity,collect);
            }
        }
        return baseMapper.selectList(wrapper);
    }


    /**
     * 根据用户id 查询所管理的电梯列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<ElevatorInfo> selectlistByUserId(Long userId) {

        List<ElevatorInfo> elevatorInfoList = new ArrayList<>();

        List<CommunityManage> communityList = userService.findCommunityByUserId(userId);
        for (CommunityManage community : communityList) {
            List<ElevatorInfo> elevatorListBy = baseMapper.selectListByCommityId(community.getCommunityId());
            elevatorInfoList.addAll(elevatorListBy);
        }
        return elevatorInfoList;
    }


    /**
     * 计算两点之间的距离
     *
     * @param latitudeStart  起点维度
     * @param longitudeStart 起点经度
     * @param latitudeEnd    终点维度
     * @param longitudeEnd   终点经度
     * @return
     */
    @Override
    public String calculationDistance(String latitudeStart, String longitudeStart, String latitudeEnd, String longitudeEnd) {
        String distance = "0";
        try {
            double radLat1 = rad(Double.parseDouble(latitudeStart));
            double radLat2 = rad(Double.parseDouble(latitudeEnd));
            double a = radLat1 - radLat2;
            double b = rad(Double.parseDouble(longitudeStart)) - rad(Double.parseDouble(longitudeEnd));
            double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                    + Math.cos(radLat1) * Math.cos(radLat2)
                    * Math.pow(Math.sin(b / 2), 2)));
            s = s * 6378.137;
            s = Math.round(s * 100d) / 100d;
            distance = String.valueOf(s);
        } catch (Exception e) {
            e.getMessage();
        }
        return distance;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过腾讯地图将经纬度转成详细地址
     *
     * @param lat 纬度
     * @param lng 经度
     *  key 开发密钥（Key） 需自行申请
     *  get_poi：返回状态。1返回，0不返回
     * @return
     */
    @Override
    public String getLatAndLng(String lat, String lng) {
        String urlString = "https://apis.map.qq.com/ws/geocoder/v1?key=" + Global.getConfig("gc.tencent_map_key") + "&location=" + lat + "," + lng + "&sig=" + getTxMapSig(lng, lat);
        String result = "";
        try {
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            // 获取地址解析结果
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
        } catch (Exception e) {
            e.getMessage();
        }
        // 转JSON格式
        JSONObject jsonObject = JSONObject.fromObject(result).getJSONObject("result");
        // 获取地址
        return jsonObject.getString("address");
    }

    //签名计算
    private String getTxMapSig(String lng, String lat) {
        String str = "/ws/geocoder/v1?key="+Global.getConfig("gc.tencent_map_key")+"&location=" + lat + "," + lng + Global.getConfig("gc.tencent_map_secret");
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }

    /**
     * 查找附近电梯
     *
     * @param latitude  纬度
     * @param longitude 经度
     * @param distance 范围
     */
    @Override
    public Integer findNeighElevatorNum(String latitude, String longitude,String distance){
        return elevatorInfoMapper.findNeighElevatorNum(latitude,longitude,distance);
    }

    /**
     * 根据小区ID查询电梯列表
     * @param communityId
     * @return
     */
    @Override
    public List<ElevatorInfo> selectListByCommityId(Long communityId){
        return elevatorInfoMapper.selectListByCommityId(communityId);
    }
}
